import 'package:flui/flui.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fzcgx_app/common/adapter_utils.dart';
import 'package:fzcgx_app/common/assets_utils.dart';
import 'package:fzcgx_app/network/http.dart';
import 'package:fzcgx_app/router/routes.dart';
import 'package:fzcgx_app/ui/my/address/page/address_page.dart';
import 'package:fzcgx_app/ui/order/page/order_grabbing_success_page.dart';
import 'package:fzcgx_app/ui/widget/custom_appbar_widget.dart';
import 'package:fzcgx_app/ui/widget/my_separator_widget.dart';
import 'package:nav_router/nav_router.dart';
import 'package:tobias/tobias.dart';

class OrderConfirmPage extends StatefulWidget {
  OrderConfirmPage({
    Key key,
    this.id,
  }) : super(key: key);
  final String id;
  @override
  _OrderConfirmPageState createState() => _OrderConfirmPageState();
}

class _OrderConfirmPageState extends State<OrderConfirmPage> {
  Map orderData;
  double webViewHeight = 100.00;
  int payIndex = 0;
  @override
  void initState() {
    requestApi();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xff141F33),
      appBar: CustomAppbar(
        backgroundColor: Color(0xff1A2537),
        title: '订单确认',
        themeColor: Colors.white,
        onTap: () {
          _popPage();
        },
      ),
      body: orderData == null
          ? Center(
              child: CupertinoActivityIndicator(
                animating: true,
                radius: 20,
              ),
            )
          : SafeArea(child: _buildSuccessWidget()),
      bottomNavigationBar: BottomAppBar(
        child: Container(
          height: AdapterUtils.getHeight(70),
          color: Color(0xff141F33),
          padding: EdgeInsets.symmetric(horizontal: AdapterUtils.getWidth(15)),
          child: Row(
            children: <Widget>[
              RichText(
                text: TextSpan(children: <InlineSpan>[
                  TextSpan(
                    text: '合计支付（元）',
                    style: TextStyle(
                      fontSize: AdapterUtils.getSp(14),
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  TextSpan(
                    text: orderData == null
                        ? '0.00'
                        : orderData['totalPrice'].toString(),
                    style: TextStyle(
                      fontSize: AdapterUtils.getSp(20),
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ]),
              ),
              Spacer(),
              InkWell(
                onTap: () {
                  postApi();

                  // routePush(
                  //   OrderGrabbingSuccessPage(),
                  // );
                },
                child: Container(
                  width: AdapterUtils.getWidth(146),
                  height: AdapterUtils.getHeight(50),
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    color: Colors.red,
                    borderRadius: BorderRadius.all(Radius.circular(26)),
                  ),
                  child: Text('确认抢单',
                      style: TextStyle(
                          color: Colors.white.withOpacity(0.4),
                          fontWeight: FontWeight.bold,
                          fontSize: AdapterUtils.getSp(18))),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildSuccessWidget() {
    return SingleChildScrollView(
        child: Column(
      children: <Widget>[
        Container(
          padding: EdgeInsets.symmetric(horizontal: AdapterUtils.getWidth(15)),
          color: Color(0xff1A2537),
          child: Column(
            children: <Widget>[
              SizedBox(height: AdapterUtils.getHeight(30)),
              InkWell(
                onTap: () {
                  Routes.navigateTo(context, AddressPage(
                    callBack: () {
                      this.requestApi();
                    },
                  ));
                },
                child: Container(
                  child: Row(
                    children: <Widget>[
                      Text(
                          orderData['isdefault'] == 0
                              ? '添加收货地址'
                              : orderData['default-address']['cityName'] +
                                  orderData['default-address']['address'],
                          style: TextStyle(
                              color: Colors.white,
                              fontWeight: FontWeight.w600,
                              fontSize: AdapterUtils.getSp(14))),
                      Spacer(),
                      Image.asset(
                          AssetsUtils.getAssetsImagesPath('arrow_right.png'))
                    ],
                  ),
                ),
              ),
              SizedBox(height: AdapterUtils.getHeight(28)),
              Container(
                height: AdapterUtils.getHeight(110),
                padding: EdgeInsets.all(10),
                decoration: BoxDecoration(
                    color: Color(0xff99A2AD),
                    borderRadius: BorderRadius.circular(12)),
                child: Row(
                  children: <Widget>[
                    FLImage(
                      image: NetworkImage(orderData['img']),
                      borderRadius: BorderRadius.circular(12),
                      fit: BoxFit.cover,
                      width: AdapterUtils.getWidth(90),
                      height: AdapterUtils.getHeight(90),
                    ),
                    SizedBox(width: AdapterUtils.getWidth(12)),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        SizedBox(height: AdapterUtils.getHeight(6)),
                        Text(orderData['proName'],
                            style: TextStyle(
                                color: Colors.white,
                                fontWeight: FontWeight.w600,
                                fontSize: AdapterUtils.getSp(16))),
                        SizedBox(height: AdapterUtils.getHeight(15)),
                        Text('单价:￥${orderData['price']}',
                            style: TextStyle(
                                color: Colors.white,
                                fontWeight: FontWeight.w500,
                                fontSize: AdapterUtils.getSp(14))),
                      ],
                    )
                  ],
                ),
              ),
              SizedBox(height: AdapterUtils.getHeight(18)),
              Container(
                child: Row(
                  children: <Widget>[
                    Text('抢单数量（件）',
                        style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.w500,
                            fontSize: AdapterUtils.getSp(14))),
                    Spacer(),
                    Text(orderData['num'],
                        style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.w500,
                            fontSize: AdapterUtils.getSp(14))),
                  ],
                ),
              ),
              SizedBox(height: AdapterUtils.getHeight(18)),
              Container(
                child: Row(
                  children: <Widget>[
                    Text('抢单单保证金（元）',
                        style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.w500,
                            fontSize: AdapterUtils.getSp(14))),
                    Spacer(),
                    Text(orderData['bond'],
                        style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.w500,
                            fontSize: AdapterUtils.getSp(14))),
                  ],
                ),
              ),
              SizedBox(height: AdapterUtils.getHeight(23)),
              MySeparatorWidget(
                color: Color(0xff3B4859),
              ),
              SizedBox(height: AdapterUtils.getHeight(26)),
              Container(
                child: Row(
                  children: <Widget>[
                    Text('合计费用（元）',
                        style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.w500,
                            fontSize: AdapterUtils.getSp(14))),
                    Spacer(),
                    Text(orderData['totalPrice'].toString(),
                        style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.w500,
                            fontSize: AdapterUtils.getSp(14))),
                  ],
                ),
              ),
              SizedBox(height: AdapterUtils.getHeight(26)),
            ],
          ),
        ),
        SizedBox(height: AdapterUtils.getHeight(10)),
        Container(
            padding:
                EdgeInsets.symmetric(horizontal: AdapterUtils.getWidth(15)),
            color: Color(0xff1A2537),
            child: Column(
              children: <Widget>[
                SizedBox(
                  height: AdapterUtils.getHeight(15),
                ),
                Text(orderData['agreeDesc'],
                    style: TextStyle(
                        color: Colors.white,
                        fontWeight: FontWeight.w500,
                        fontSize: AdapterUtils.getSp(14))),
//                 Text('''1.订单由工厂或公司发布，订单分普通单和加急单，其
// 中加急单需要用户支付保证金方可抢单。

// 2.用户抢单前需先添加收货地址

// 3.支付后的订单，会通知发布方，获取联系方式安排交
// 易，有疑问请联系美策客服 400-716-0000''',
//                     style: TextStyle(
//                         color: Colors.white,
//                         fontWeight: FontWeight.w500,
//                         fontSize: AdapterUtils.getSp(14))),
                SizedBox(
                  height: AdapterUtils.getHeight(15),
                ),
              ],
            ))
      ],
    ));
  }

  void requestApi() {
    Http.instance.post('home/bale-sure-one', {
      'id': widget.id,
    }, onSuccess: (data) {
      if (mounted) {
        setState(() {
          orderData = data;
        });
      }
    }, onError: (error) {}, onFail: (fail) {}, complete: () {});
  }

  void postApi() {
    if (orderData['isdefault'] == 0) {
      FLToast.showText(text: '请设置收货地址');
      return;
    }
    if (orderData['isbond'] == 1) {
      //  _openModalBottomSheet();
      //   return;
      if (orderData['isbondok'] == 0) {
        _openModalBottomSheet();
        return;
      }
    }
    var dismiss = FLToast.loading(text: '正在抢单...');
    Http.instance.post(
        'home/bale-task-add', {'id': widget.id, 'addressId': orderData['default-address']['addressId']},
        onSuccess: (data) {
          // FLToast.showSuccess(text:'保存成功');
          routePush(OrderGrabbingSuccessPage());
        },
        onError: (error) {},
        onFail: (fail) {},
        complete: () {
          dismiss();
        });
  }

  void _openModalBottomSheet() {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return StatefulBuilder(
            builder: (context, mSetState) {
              return Container(
                  height: AdapterUtils.getHeight(500),
                  child: SingleChildScrollView(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        SizedBox(
                          height: AdapterUtils.getHeight(15),
                        ),
                        Text('您需支付保证金',
                            style: TextStyle(
                                color: Color(0xff606B79),
                                fontWeight: FontWeight.w400,
                                fontSize: AdapterUtils.getSp(14))),
                        SizedBox(
                          height: AdapterUtils.getHeight(16),
                        ),
                        RichText(
                          text: TextSpan(children: <InlineSpan>[
                            TextSpan(
                              text: '￥',
                              style: TextStyle(
                                fontSize: AdapterUtils.getSp(24),
                                color: Color(0xff141F33),
                                fontWeight: FontWeight.w400,
                              ),
                            ),
                            TextSpan(
                              text: orderData['bond'],
                              style: TextStyle(
                                fontSize: AdapterUtils.getSp(44),
                                color: Color(0xff141F33),
                                fontWeight: FontWeight.w400,
                              ),
                            ),
                          ]),
                        ),
                        SizedBox(
                          height: AdapterUtils.getHeight(15),
                        ),
                        Text('请选择支付方式',
                            style: TextStyle(
                                color: Color(0xff3B4859),
                                fontWeight: FontWeight.w400,
                                fontSize: AdapterUtils.getSp(14))),
                        SizedBox(
                          height: AdapterUtils.getHeight(15),
                        ),
                        InkWell(
                          onTap: () {
                            if (mounted) {
                              mSetState(() {
                                this.payIndex = 1;
                              });
                            }
                          },
                          child: Container(
                            margin: EdgeInsets.symmetric(
                                horizontal: AdapterUtils.getWidth(15)),
                            padding: EdgeInsets.symmetric(
                                horizontal: AdapterUtils.getWidth(23),
                                vertical: AdapterUtils.getHeight(12)),
                            decoration: BoxDecoration(
                                border: Border.all(
                                    color: this.payIndex == 1
                                        ? Color(0xffFF3D3E)
                                        : Color(0xffCCCCCC),
                                    width: 1),
                                borderRadius:
                                    BorderRadius.all(Radius.circular(22))),
                            child: Row(
                              children: <Widget>[
                                Image.asset(AssetsUtils.getAssetsImagesPath(
                                    'weixin.png')),
                                SizedBox(
                                  width: AdapterUtils.getWidth(14),
                                ),
                                Text('微信支付',
                                    style: TextStyle(
                                        color: Color(0xff141F33),
                                        fontWeight: FontWeight.w500,
                                        fontSize: AdapterUtils.getSp(14))),
                                Spacer(),
                                payIndex == 1
                                    ? Image.asset(
                                        AssetsUtils.getAssetsImagesPath(
                                            'check_red.png'))
                                    : Container(),
                              ],
                            ),
                          ),
                        ),
                        SizedBox(
                          height: AdapterUtils.getHeight(15),
                        ),
                        InkWell(
                          onTap: () {
                            if (mounted) {
                              mSetState(() {
                                this.payIndex = 2;
                              });
                            }
                          },
                          child: Container(
                            margin: EdgeInsets.symmetric(
                                horizontal: AdapterUtils.getWidth(15)),
                            padding: EdgeInsets.symmetric(
                                horizontal: AdapterUtils.getWidth(23),
                                vertical: AdapterUtils.getHeight(12)),
                            decoration: BoxDecoration(
                                border: Border.all(
                                    color: this.payIndex == 2
                                        ? Color(0xffFF3D3E)
                                        : Color(0xffCCCCCC),
                                    width: 1),
                                borderRadius:
                                    BorderRadius.all(Radius.circular(22))),
                            child: Row(
                              children: <Widget>[
                                Image.asset(AssetsUtils.getAssetsImagesPath(
                                    'zhifubao.png')),
                                SizedBox(
                                  width: AdapterUtils.getWidth(14),
                                ),
                                Text('支付宝支付',
                                    style: TextStyle(
                                        color: Color(0xff141F33),
                                        fontWeight: FontWeight.w500,
                                        fontSize: AdapterUtils.getSp(14))),
                                Spacer(),
                                payIndex == 2
                                    ? Image.asset(
                                        AssetsUtils.getAssetsImagesPath(
                                            'check_red.png'))
                                    : Container(),
                              ],
                            ),
                          ),
                        ),
                        SizedBox(
                          height: AdapterUtils.getHeight(15),
                        ),
                        InkWell(
                          onTap: () {
                            if (this.payIndex == 0) {
                              FLToast.showText(text: '请选择支付方式');
                              return;
                            }
                            pay();
                          },
                          child: Container(
                            width: AdapterUtils.screenWidth(),
                            alignment: Alignment.center,
                            padding: EdgeInsets.symmetric(
                                vertical: AdapterUtils.getHeight(10)),
                            margin: EdgeInsets.symmetric(
                                horizontal: AdapterUtils.getWidth(15)),
                            decoration: BoxDecoration(
                                color: Color(0xffFF3D3E),
                                borderRadius:
                                    BorderRadius.all(Radius.circular(26))),
                            child: Text('确认支付',
                                style: TextStyle(
                                    color: Colors.white,
                                    fontWeight: FontWeight.bold,
                                    fontSize: AdapterUtils.getSp(18))),
                          ),
                        ),
                        SizedBox(
                          height: AdapterUtils.getHeight(15),
                        ),
                        InkWell(
                          onTap: () {
                            pop();
                          },
                          child: Text('取消支付',
                              style: TextStyle(
                                  color: Color(0xff99A2AD),
                                  fontWeight: FontWeight.w400,
                                  fontSize: AdapterUtils.getSp(14))),
                        ),
                        SizedBox(
                          height: AdapterUtils.getHeight(15),
                        ),
                      ],
                    ),
                  ));
            },
          );
        }).then((value) {
      print(value);
    });
  }

  void pay() async {
    if (this.payIndex == 1) {
    } else if (this.payIndex == 2) {
      isAliPayInstalled().then((isInstalled) {
        if (isInstalled) {
          pop();
          var dismiss = FLToast.loading(text: '正在加载...');
          Http.instance.post(
              'order/pay-bond-add',
              {
                'type': payIndex.toString(),
                'id': widget.id,
              },
              onSuccess: (data) {
                aliPay(data['pay_info']).then((value) {
                  LogUtil.e(value);
                  if (value['resultStatus'] == 9000) {
                    this.payIndex = 0;
                    routePush(OrderGrabbingSuccessPage());
                  }
                });
              },
              onError: (error) {},
              onFail: (fail) {},
              complete: () {
                dismiss();
              });
        } else {
          FLToast.showText(text: '非常抱歉！您没有安装支付宝');
        }
      });
    }
  }

  _popPage() {
    showDialog(
        context: context,
        builder: (context) {
          return Material(
            type: MaterialType.transparency,
            child: Center(
                child: Container(
              height: 135,
              width: 280,
              color: Colors.white,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  SizedBox(
                    height: 35,
                  ),
                  Align(
                    child: Text('离开可能会错失此订单',
                        style: TextStyle(
                            color: Color(0xff141F33),
                            fontWeight: FontWeight.w400,
                            fontSize: AdapterUtils.getSp(16))),
                    alignment: Alignment.center,
                  ),
                  SizedBox(
                    height: 27,
                  ),
                  Container(
                    height: 1,
                    color: Color(0xff191F25).withOpacity(0.08),
                  ),
                  Container(
                    height: 44,
                    child: Row(
                      children: <Widget>[
                        Expanded(
                            child: InkWell(
                          onTap: () {
                            Navigator.pop(context, 0);
                          },
                          child: Container(
                            alignment: Alignment.center,
                            child: Text('取消',
                                style: TextStyle(
                                    color: Color(0xff99A2AD),
                                    fontWeight: FontWeight.w500,
                                    fontSize: AdapterUtils.getSp(17))),
                          ),
                        )),
                        Container(
                          width: 1,
                          color: Color(0xff191F25).withOpacity(0.08),
                        ),
                        Expanded(
                            child: InkWell(
                          onTap: () {
                            Navigator.pop(context, 1);
                          },
                          child: Container(
                            alignment: Alignment.center,
                            child: Text('确认',
                                style: TextStyle(
                                    color: Color(0xffFF3D3E),
                                    fontWeight: FontWeight.w500,
                                    fontSize: AdapterUtils.getSp(17))),
                          ),
                        ))
                      ],
                    ),
                  )
                ],
              ),
            )),
          );
        }).then((value) {
      if (value == 1) {
        pop();
      }
    });
  }
}
